<?php
/**
 * Extend the Authenticator class to add Zend_Session support
 *
 * @author @@AUTHOR@@
 * @copyright @@AUTHOR@@ @@YEAR@@
 * @version @@VERSION@@
 * @package Extensions
 * @subpackage DbSession
 * @license  @@LICENCE_URL@@ @@LICENCE@@
 *
 * $Id: People.Class.DbSessionAuthenticator.php 322 2008-10-11 13:03:00Z dinoboff $
 * $HeadURL: http://vanilla-friends.googlecode.com/svn/trunk/DbSession/library/People/People.Class.DbSessionAuthenticator.php $
 */

if (!defined('IN_VANILLA')) exit();

/**
 * @global Context $Context
 */
global $Context;
include_once $Context->Configuration['LIBRARY_PATH'] . '/People/People.Class.Authenticator.php';

/**
 * Make Authenticator use $Context->Session instead of $_SESSION
 * @package Extensions
 * @subpackage DbSession
 */
class DbSessionAuthenticator extends Authenticator {

	function DeAuthenticate() {
		$this->Context->Session->Destroy();

		// Destroy the cookies as well
		setcookie($this->Context->Configuration['COOKIE_USER_KEY'],
			' ',
			time()-3600,
			$this->Context->Configuration['COOKIE_PATH'],
			$this->Context->Configuration['COOKIE_DOMAIN']);
		unset($_COOKIE[$this->Context->Configuration['COOKIE_USER_KEY']]);
		setcookie($this->Context->Configuration['COOKIE_VERIFICATION_KEY'],
			' ',
			time()-3600,
			$this->Context->Configuration['COOKIE_PATH'],
			$this->Context->Configuration['COOKIE_DOMAIN']);
		unset($_COOKIE[$this->Context->Configuration['COOKIE_VERIFICATION_KEY']]);
		return true;
	}

	function GetIdentity() {
		$UserID = $this->Context->Session->GetVariable(
			$this->Context->Configuration['SESSION_USER_IDENTIFIER'], 'int');

		if ($UserID == 0) {
			// UserID wasn't found in the session, so attempt to retrieve it from the cookies
			// Retrieve cookie values
			$CookieUserID = ForceIncomingCookieString($this->Context->Configuration['COOKIE_USER_KEY'], '');
			$VerificationKey = ForceIncomingCookieString($this->Context->Configuration['COOKIE_VERIFICATION_KEY'], '');
			$UserManager = $this->Context->ObjectFactory->NewContextObject(
				$this->Context, 'UserManager');

			$UserID = $UserManager->ValidateVerificationKey($CookieUserID, $VerificationKey);
			if ($UserID > 0) {
				// 1. Update the user's information
				$UserManager->UpdateUserLastVisit($UserID, $VerificationKey);

				// 2. Log the user's IP address
				$UserManager->AddUserIP($UserID);

				// If it has now been found, set up the session.
				$this->AssignSessionUserID($UserID);
			}
		}
		return $UserID;
	}

 	function AssignSessionUserID($UserID) {
 		if ($UserID > 0) {
			$this->Context->Session->SetVariable(
				$this->Context->Configuration['SESSION_USER_IDENTIFIER'], $UserID);
 		}
 	}
}